import { API_BASE_URL, handleApiResponse, type ApiResponse } from './config'

// API响应数据结构 - 广告位
export interface ApiSpaceItem {
  id: string | null
  name: string | null
  mediaId: string | null
  mediaName: string | null
  type: number | null
  status: number | null
  width: number | null
  height: number | null
  floorPrice: number | null
  createTime: string | null
  updateTime: string | null
}

export interface ApiSpaceResponse {
  records: ApiSpaceItem[]
  totalRow: number
  pageNumber: number
  pageSize: number
}

export interface SpacePageParams {
  current: number
  size: number
  name?: string
  mediaId?: string
}

// 获取广告位分页数据
export const fetchSpaceData = async (params: SpacePageParams): Promise<ApiSpaceResponse> => {
  try {
    const response = await fetch(`${API_BASE_URL}/space/page`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<ApiSpaceResponse>(response)
  } catch (error) {
    console.error('获取广告位数据失败:', error)
    throw error
  }
}

// 获取广告位列表（不分页）
export const fetchSpaceList = async (params: SpacePageParams): Promise<ApiSpaceResponse> => {
  try {
    const response = await fetch(`${API_BASE_URL}/space/list`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<ApiSpaceResponse>(response)
  } catch (error) {
    console.error('获取广告位列表失败:', error)
    throw error
  }
}

// 创建广告位
export const createSpace = async (data: Partial<ApiSpaceItem>): Promise<{ success: boolean; message?: string }> => {
  try {
    const response = await fetch(`${API_BASE_URL}/space/create`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    return { success: true }
  } catch (error) {
    console.error('创建广告位失败:', error)
    return { success: false, message: '创建失败' }
  }
}

// 更新广告位
export const updateSpace = async (id: string, data: Partial<ApiSpaceItem>): Promise<{ success: boolean; message?: string }> => {
  try {
    const response = await fetch(`${API_BASE_URL}/space/update`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ id, ...data })
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    return { success: true }
  } catch (error) {
    console.error('更新广告位失败:', error)
    return { success: false, message: '更新失败' }
  }
}

// 删除广告位
export const deleteSpace = async (id: string): Promise<{ success: boolean; message?: string }> => {
  try {
    const response = await fetch(`${API_BASE_URL}/space/delete`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ id })
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    return { success: true }
  } catch (error) {
    console.error('删除广告位失败:', error)
    return { success: false, message: '删除失败' }
  }
}

// 日志相关接口和数据结构
export interface LogItem {
  id: string
  operationType: number
  operator: string
  operationTime: string
  description: string
  ip: string
}

export interface LogResponse {
  records: LogItem[]
  totalRow: number
  pageNumber: number
  pageSize: number
}

export interface LogPageParams {
  current: number
  size: number
  adspaceId?: string
}

// 获取日志数据
export const fetchLogData = async (): Promise<LogResponse> => {
  try {
    const response = await fetch(`${API_BASE_URL}/server/list`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<LogResponse>(response)
  } catch (error) {
    console.error('获取日志数据失败:', error)
    throw error
  }
}

// 推送日志记录接口
interface PushLogRecordParams {
  url: string
  adSpaceId: string
  logCount: number
  logEnable: boolean
  logSuccess: boolean
}

export const pushLogRecord = async (params: PushLogRecordParams): Promise<{ success: boolean; message?: string }> => {
  try {
    const response = await fetch(`${API_BASE_URL}/server/pushLogRecord`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    return { success: true }
  } catch (error) {
    console.error('推送日志记录失败:', error)
    return { success: false, message: '推送日志记录失败' }
  }
}

// 广告位最后10条记录接口
export interface Last10RecordItem {
  adspaceId: string
  request: string
  response: string
  insertTime: string
}

export interface Last10RecordsResponse {
  records: Last10RecordItem[]
  totalRow: number
}

// 获取广告位最后10条记录
export const fetchLast10Records = async (adspaceId: string): Promise<Last10RecordsResponse> => {
  try {
    const response = await fetch(`${API_BASE_URL}/space/last10Records`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ adspaceId })
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<Last10RecordsResponse>(response)
  } catch (error) {
    console.error('获取广告位最后10条记录失败:', error)
    throw error
  }
}